package com.gec.hawaste.shiro;

import com.gec.hawaste.entity.SysUser;
import com.gec.hawaste.service.ISysResourceService;
import com.gec.hawaste.service.ISysRoleService;
import com.gec.hawaste.service.ISysUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysResourceService sysResourceService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        System.out.println("用户认证的账号：" + username);
        SysUser loginUser = sysUserService.findUserByUsername(username);
        if (loginUser==null){
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                loginUser,
                loginUser.getPassword(),
                ByteSource.Util.bytes(loginUser.getUsername()),
                "MyRealm"
        );
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        SysUser user = (SysUser) principal.getPrimaryPrincipal();
        List<String> roles = new ArrayList<>();
        List<String> resourceList = new ArrayList<>();

        // 遍历角色列表
        sysRoleService.selectByUid(user.getId()).forEach(sysRole -> {
            if (!roles.contains(sysRole.getName())){
                roles.add(sysRole.getName());
            }
        });
        // 遍历权限列表
        sysResourceService.selectByUid(user.getId()).forEach(resource -> {
            if (!resourceList.add(resource.getPermissionStr())){
                resourceList.add(resource.getPermissionStr());
            }
        });

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(resourceList);

        return info;
    }


}
